package cn.bdqn.controller;

import cn.bdqn.dto.Dto;
import cn.bdqn.pojo.ItripUser;
import cn.bdqn.service.TokenService;
import cn.bdqn.service.UserService;
import cn.bdqn.util.UrlUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 2018/9/4
 * 第三方微信登录
 */

@Controller
public class WxLoginController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 获取code
     *
     *   需要修改  appId  ; redirect_uri  ; response_type;  scope
     *
     * @param response
     */
    @RequestMapping(value = "/wechat/login")
    public void wechatLogin(HttpServletResponse response){
        String url="https://open.weixin.qq.com/connect/qrconnect?appid=wx9168f76f000a0d4c&redirect_uri=http%3a%2f%2fitrip.project.bdqn.cn%2fauth%2fvendors%2fwechat%2fcallback&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 通过code 换 access_token
     *
     * appid  secret   code  grant_type
     *
     *  需要修改appId
     *
     * @param code
     * @param status
     * @param response
     */
    @RequestMapping(value = "/wechat/callback")
        public void callBack(String code, String status, HttpServletResponse response, HttpServletRequest request){
        String accessUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx9168f76f000a0d4c&secret=8ba69d5639242c3bd3a69dffe84336c1&code="+
                code+"&grant_type=authorization_code";
        response.setContentType("text/html;charset=utf-8");
        //请求地址获取 access_token
        String jsonStr=UrlUtils.loadURL(accessUrl);
        Map<String,Object> accessMap= JSON.parseObject(jsonStr,Map.class);
      /*  String accessToken=accessMap.get("access_token");
        String openId=accessMap.get("openId");*/

        try {
            //验证本地是否已经存在该用户
            ItripUser itripUser =userService.findByUsername(accessMap.get("openid").toString());
            if (null == itripUser){
                //如果没有 就添加
                itripUser=new ItripUser();
                //微信用户openid作为本地库用户名
                itripUser.setUserCode(accessMap.get("openId").toString());
                itripUser.setUserType(1);
                itripUser.setUserName(accessMap.get("openId").toString());
                itripUser.setCreationDate(new Date());
                itripUser.setActivated(1);
                //调用insert方法添加信息
                userService.itripCreateUser(itripUser);

            }

            String token = tokenService.getToken(
                    request.getHeader("user-agent"), itripUser);
            tokenService.save(token, itripUser);

            //返回前端处理
            StringBuilder loginPage=new StringBuilder();
            loginPage.append("http://itrip.project.bdqn.cn/#/login");
            loginPage.append("?user_type=1&token="+token);
            loginPage.append("&access_token="+accessMap.get("access_token").toString());
            loginPage.append("&expires_in="+accessMap.get("expires_in").toString());
            loginPage.append("&refresh_token="+accessMap.get("refresh_token").toString());
            loginPage.append("&openid="+accessMap.get("openid").toString());
            response.sendRedirect(loginPage.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取微信信息
     * @param accessToken 微信会话凭据
     * @param openid  微信用户唯一标识
     * @return
     */
    @ApiOperation(value = "获取微信用户信息", httpMethod = "GET", protocols = "HTTP", produces = "application/json", response = Dto.class, notes = "微信登录后，提供客户端获取用户信息操作")
    @RequestMapping(value = "/wechat/user/info", method = RequestMethod.GET,produces= "application/json")
    @ResponseBody
    public Dto wechatUserInfo(@RequestParam String accessToken, @RequestParam String openid){
            Dto dto=new Dto();
            try {
                String userInfoJson = UrlUtils.loadURL("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid);
                Map<String, Object> userInfo = JSON.parseObject(userInfoJson, Map.class);
                dto.setCode("0000");
                dto.setMsg("获取信息成功");
                dto.setData(userInfo);
                dto.setSuccess("true");

                return dto;
            }catch (Exception e){
                e.printStackTrace();
                dto.setCode("10086");
                dto.setMsg("获取信息失败");
                dto.setSuccess("false");
                return dto;
            }

    }







}
